package com.app.sanyou.view.viewpager;


import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.app.sanyou.R;
import com.app.sanyou.common.CallListener;
import com.app.sanyou.common.JsonResult;
import com.app.sanyou.constants.Request;
import com.app.sanyou.entity.ProductVo;
import com.app.sanyou.utils.HttpUtil;
import com.app.sanyou.utils.StringUtil;
import com.app.sanyou.utils.UserUtil;
import com.app.sanyou.view.login.LoginActivity;
import com.glsurfaceview.TextureCameraActivity;
import com.google.gson.Gson;
import com.tencent.yolov5ncnn.Permission;

public class ScanFragment extends Fragment {

    private static final String DECODED_CONTENT_KEY = "codedContent";
    private static final String DECODED_BITMAP_KEY = "codedBitmap";
    private static final int REQUEST_CODE_SCAN = 0x0000;

    /* 扫码结果接收广播地址 */
    public static final String ACTION_BROADCAST_RECEIVER = "com.android.decodewedge.decode_action";
    public static final String EXTRA_BARCODE_STRING = "com.android.decode.intentwedge.barcode_string"; /* 扫码结果 */
    public static final String EXTRA_BARCODE_TYPE = "com.android.decode.intentwedge.barcode_type";    /* 条码类型 */

    /* 控制扫码开关广播地址, 设备扫码按键默认会触发扫码，APP端一般需要接收结果即可，不需要控制扫码，除非需要在APP里面自己触发扫码 */
    public static final String ACTION_START_DECODE = "com.android.decode.action.START_DECODE";
    public static final String ACTION_STOP_DECODE = "com.android.decode.action.STOP_DECODE";
    //begin:理学院的扫码接口相关
    MyDymnicReveiver myDymnicReveiver=new MyDymnicReveiver();
    //end:理学院的扫码接口相关
    private BroadcastReceiver receiver = null;
    private IntentFilter filter = null;

    private TextView search_btn;
    private EditText query_text;
    private ImageView ivDelete;

    private ImageButton btn_scan;
    private TextView tv_scanResult;

    private Context context;
    private TabViewPagerActivity tabViewPagerActivity;


    private String scanCode;
    private String requestTag="1";
    private String userId;

    private Handler handler = new Handler();

    private CallListener checkExistListener = new CallListener() {
        Gson gson = new Gson();
        private ProductVo productVo;
        @Override
        public void success(JsonResult result) {
            productVo = gson.fromJson(gson.toJson(result.getData()), ProductVo.class);
            //Log.d("Hu",productVo.toString());
            if(productVo==null){
                this.failure(result);
                return;
            }
            tv_scanResult.setText("点击扫码");
            Intent intent = new Intent(context, ScanResultActivity.class);
            //intent.putExtra("scanCode",scanCode);
            intent.putExtra("productVo",productVo);
            //Log.d("Hu",productVo.toString());
            startActivity(intent);
        }

        @Override
        public void failure(JsonResult result) {
            getActivity().runOnUiThread(()->Toast.makeText(context,"阴极板不存在!",Toast.LENGTH_SHORT).show());
        }
    };
    /*private CallListener productListener = new CallListener() {
        @Override
        public void success(JsonResult result) {
            Intent intent = new Intent(context, ScanResultActivity.class);
            intent.putExtra("scanCode",scanCode);
            intent.putExtra("tag","1");
            startActivity(intent);
        }

        @Override
        public void failure(JsonResult result) {
            getActivity().runOnUiThread(()->Toast.makeText(context,"阴极板不存在!",Toast.LENGTH_SHORT).show());
        }
    };*/

    public static ScanFragment getInstance(Context context,TabViewPagerActivity tabViewPagerActivity) {
        ScanFragment scanFragment = new ScanFragment();
        scanFragment.context = context;
        scanFragment.tabViewPagerActivity = tabViewPagerActivity;
        return scanFragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.scan_fragment,null);

        //begin:理学院的扫码接口相关
        //动态注册监听类 监听关键字"close_camera_main"
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction("close_camera_main");
        tabViewPagerActivity.registerReceiver(myDymnicReveiver,intentFilter);
        //end:理学院的扫码接口相关
        //初始化view
        initView(view);
        //初始化点击事件
        initClickListener();

        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        Permission.checkPermission(tabViewPagerActivity);
    }

    @Override
    public void onResume() {
        super.onResume();
        query_text.setText("");

        receiver = new DecodeWedgeIntentReceiver();
        filter = new IntentFilter();
        filter.addAction(ACTION_BROADCAST_RECEIVER);

        this.context.registerReceiver(receiver,filter);
    }

    @Override
    public void onPause() {
        super.onPause();

        this.context.unregisterReceiver(receiver);
        receiver = null;
        filter = null;
    }

    //begin:理学院的扫码接口相关
    @Override
    public void onDestroy() {
        //最好销毁类时候注销掉监听类
        if (myDymnicReveiver!=null){
            tabViewPagerActivity.unregisterReceiver(myDymnicReveiver);
        }
        super.onDestroy();
    }
    //end:理学院的扫码接口相关

    /**
     * 初始化view
     */
    private void initView(View view){
        tv_scanResult = view.findViewById(R.id.tv_scanResult);
        btn_scan = view.findViewById(R.id.btn_scan);
        /*btn_scan.setOnTouchListener((v, event) -> {
            final int action = event.getAction();
            switch (action){
                case MotionEvent.ACTION_DOWN:
                    try {
                        startDecode();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    try {
                        stopDecode();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
            }
            return true;
        });*/
        userId = UserUtil.getUserId(context);
        if(StringUtil.isNull(userId)){
            UserUtil.loginOut(context);
            Intent intent = new Intent(context, LoginActivity.class);
            startActivity(intent);
        }
        Intent mSendIntent = new Intent("com.android.action.setPropertyInt");
        mSendIntent.putExtra("PropertyID", 0x30D47);
        mSendIntent.putExtra("PropertyInt", 1);
        this.context.sendBroadcast(mSendIntent);
//        Intent mSendIntent3 = new Intent("com.android.action.setPropertyInt");
//        mSendIntent3.putExtra("PropertyID", 0x11172);
//        mSendIntent3.putExtra("PropertyInt", 1);
//        this.context.sendBroadcast(mSendIntent3);
//        Intent mSendIntent4 = new Intent("com.android.action.setPropertyInt");
//        mSendIntent4.putExtra("PropertyID", 0x11176);
//        mSendIntent4.putExtra("PropertyInt", 1);
//        this.context.sendBroadcast(mSendIntent4);
        Intent mSendIntent2 = new Intent("com.android.action.setPropertyString");
        mSendIntent2.putExtra("PropertyID", 0x0027);
        mSendIntent2.putExtra("PropertyString", "");
        this.context.sendBroadcast(mSendIntent2);

        search_btn = view.findViewById(R.id.search_btn);
        query_text = view.findViewById(R.id.query_text);
        ivDelete = view.findViewById(R.id.ivDelete);
    }

    private void startDecode(){
        Intent myIntent = new Intent();
        myIntent.setAction(ACTION_START_DECODE);
        this.context.sendBroadcast(myIntent);
    }

    private void stopDecode(){
        Intent myIntent = new Intent();
        myIntent.setAction(ACTION_STOP_DECODE);
        this.context.sendBroadcast(myIntent);
    }

    //扫码机器相关的
    public class DecodeWedgeIntentReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(action.equals(ACTION_BROADCAST_RECEIVER)){
                //接收广播，并读取扫码结果
                scanCode = intent.getStringExtra(EXTRA_BARCODE_STRING);
                String codeType = intent.getStringExtra(EXTRA_BARCODE_TYPE);
                if(scanCode != null){
                    tv_scanResult.setText(codeType + ":" + scanCode);

                    //判断阴极板是否存在
                    /*HttpUtil.get(Request.URL + "/app/product/checkExist?code=" + scanCode,checkExistListener);*/
                    HttpUtil.get(Request.URL + "/app/scancode/getInfo?scanCode=" + scanCode +
                            "&userId=" + userId + "&tag=" + requestTag,checkExistListener);
                }
            }
        }
    }

    /**
     * 初始化点击事件
     */
    private void initClickListener(){
        //扫码按钮点击事件
        btn_scan.setOnClickListener(v -> {
            goScan();
            /*//动态权限申请
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(tabViewPagerActivity, new String[]{Manifest.permission.CAMERA}, 1);
            } else {
                goScan();
            }*/
        });

        //设置删除图片的点击事件
        ivDelete.setOnClickListener(v->{
            query_text.setText("");
            ivDelete.setVisibility(View.GONE);
        });

        //EditText添加监听
        query_text.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(s.length()==0)
                    ivDelete.setVisibility(View.GONE);
                else{
                    ivDelete.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        //搜索按钮的点击事件
        search_btn.setOnClickListener(v->{
            scanCode = query_text.getText().toString();
            if(StringUtil.isNull(scanCode)){
                Toast.makeText(context,"阴极板编码不能为空!",Toast.LENGTH_SHORT).show();
            }else{

                //判断阴极板是否存在
                /*HttpUtil.get(Request.URL + "/app/product/checkExist?code=" + scanCode,checkExistListener);*/
                HttpUtil.get(Request.URL + "/app/scancode/getInfo?scanCode=" + scanCode +
                        "&userId=" + userId + "&tag=" + requestTag,checkExistListener);
            }
        });
    }

    /**
     * 跳转到扫码界面扫码
     */
    private void goScan(){
        Intent intent = new Intent(context, TextureCameraActivity.class);
        startActivityForResult(intent, REQUEST_CODE_SCAN);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    goScan();
                } else {
                    Toast.makeText(context, "你拒绝了权限申请，可能无法打开相机扫码哟！", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                //返回的文本内容
                String content = data.getStringExtra(DECODED_CONTENT_KEY);
                //返回的BitMap图像
                Bitmap bitmap = data.getParcelableExtra(DECODED_BITMAP_KEY);

                //tv_scanResult.setText("你扫描到的内容是：" + content);
            }
        }
    }
    //begin:理学院的扫码接口相关
    //监听类
    class MyDymnicReveiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            //if(intent!=null&&intent.getAction().equals(BroadOrderActivity.ORDER_ACTION))
            if(intent!=null){
                //获取KeyId为result的 具体内容
                String result=intent.getStringExtra("result");
                Toast.makeText(context,"跳转中", Toast.LENGTH_SHORT).show();
                scanCode = result;
                if(StringUtil.isNull(scanCode)){
                    Toast.makeText(context,"阴极板编码不能为空!",Toast.LENGTH_SHORT).show();
                }else{
                    //判断阴极板是否存在
                    /*HttpUtil.get(Request.URL + "/app/product/checkExist?code=" + scanCode,checkExistListener);*/
                    HttpUtil.get(Request.URL + "/app/scancode/getInfo?scanCode=" + scanCode +
                            "&userId=" + userId + "&tag=" + requestTag,checkExistListener);
                }
            }
        }
    }
    //end:理学院的扫码接口相关

}
